package org.trademarket.trader.domain;

import java.util.ArrayList;
import java.util.List;

import org.springframework.util.Assert;

public abstract class Trader {

	private String name;
	private Trade tradeToPropose;
	private TradeType tradeType;
	private List<Proposal> proposals = new ArrayList<Proposal>();

	public Trader(String name, TradeType tradeType) {
		Assert.hasText(name, "Trader must have a name");
		Assert.notNull(tradeType, "TradeType cannot be null");
		this.name = name;
		this.tradeType = tradeType;
	}

	public void setTradeToPropose(Trade trade) {
		if (hasTradeToPropose())
			throw new IllegalArgumentException(
					"Trade was already set. Call propose before setting trade again");
		Assert.notNull(trade, "Trade cannot be null");
		this.tradeToPropose = trade;
	}

	public Proposal propose() {
		if (!hasTradeToPropose())
			throw new IllegalStateException("Trader doesn't have trade to propose");
		return makeProposalFromTrade();
	}

	public boolean hasTradeToPropose() {
		return tradeToPropose != null;
	}

	private Proposal makeProposalFromTrade() {
		Proposal proposal = new Proposal(this);
		makeCurrentTradeProposed();
		proposals.add(proposal);
		return proposal;
	}

	private void makeCurrentTradeProposed() {
		tradeToPropose = null;
	}

	public boolean isCunsomer() {
		return tradeType == TradeType.BUY;
	}

	public boolean isSeller() {
		return tradeType == TradeType.SELL;
	}

	public String getName() {
		return name;
	}

	public Trade getTradeToPropose() {
		return tradeToPropose;
	}

	public TradeType getTradeType() {
		return tradeType;
	}

	@Override
	public String toString() {
		return tradeType == TradeType.BUY ? "Consumer" : "Seller" 
			   + " [name=" + name + "]";
	}

}
